package com.whynot.frame.basic.mybatis.service;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Condition;

import com.google.common.collect.Lists;
import com.whynot.frame.basic.mybatis.conroller.model.BaseField;
import com.whynot.frame.basic.mybatis.conroller.model.TreeNodes;
import com.whynot.frame.basic.mybatis.model.BaseModel;
import org.apache.commons.beanutils.BeanUtils;

import java.util.Collection;
import java.util.Map;

/**
 * 描    述:基础的Service接口
 * 创建时间: 2018/07/10
 */
public class BaseTreeServiceImpl<M extends BaseMapper<T>, T extends BaseModel>  extends BaseServiceImpl<M, T> {

    /**
     * 功能说明:取得用于显示节点ID的属性的名称。默认是"id"
     */
    public String getIdPropertyName(){
        return "id";
    }

    /**
     * 获取根节点结合
     * @param param
     * @return
     */
    public Collection<T> getRoot(Map<String, String> param){
        Condition con=Condition.create();
        String id=param.get(BaseField.TABLE_ID);
        //在组合条件的时候必须调用MybatisUtil.getColumn方法，目的是为了支持属性和字段名称，统一返回数据库支持的名称
        if(null!=id){
            con.eq(BaseField.TABLE_PARENT_ID,id);
        }else{
            con.isNull(BaseField.TABLE_PARENT_ID);
        }
        con.orderBy(BaseField.TABLE_ID,true);
        return this.selectList(con);
    }

    /**
     * 获取子节点集合
     * @param param
     * @param bean
     * @return
     */
    public Collection<T> getChildren(Map<String, String> param, T bean) throws Exception {
        Condition con=Condition.create();
        con.eq(BaseField.TABLE_PARENT_ID, BeanUtils.getProperty(bean,BaseField.TABLE_ID));
        con.orderBy(BaseField.TABLE_ID,true);
        return this.selectList(con);
    }

    /**
     * 递归查找子节点，组成树结构
     * @param param
     * @param list
     * @param flag true同步 faslse异步
     * @param propertyName
     * @return
     * @throws Exception
     */
    public Collection<TreeNodes> findTreeNodes(Map<String, String> param,Collection<T> list,Boolean flag,String propertyName) throws Exception{
        Collection<TreeNodes> collection = Lists.newArrayList();
        for(T t:list){
            TreeNodes childnode=new TreeNodes();
            childnode.setId(BeanUtils.getProperty(t, this.getIdPropertyName()));
            childnode.setName(BeanUtils.getProperty(t, propertyName));
            Collection<T> childlist=this.getChildren(param,t);
            if(childlist!=null&&childlist.size()>0){
                childnode.setOpen(true);
                childnode.setParent(true);
                if(flag){
                    childnode.setChildren(this.findTreeNodes(param,childlist,true,propertyName));
                }
            }
            //供子类扩展
            this.beforeShowTree(childnode,t);
            collection.add(childnode);
        }
        return collection;
    }

    /**
     * 功能说明:供子类扩展 (默认空实现)
     */
    protected void beforeShowTree(TreeNodes node, T t){

    }
}